/**
 *
 */
package com.fulihui.wgj.auth.controller;

import org.bouncycastle.crypto.Digest;
import org.bouncycastle.jcajce.provider.util.DigestFactory;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.util.Arrays;

/**
 * @author Young
 */
@RestController
public class WxCheckController {
    private static final Logger logger = LoggerFactory.getLogger(WxCheckController.class);
    // 自定义 token
    private static final String TOKEN = "openwxcore";

    /**
     * 验证微信token
     *
     * @param request
     * @return
     */
    @RequestMapping("/checkwxtoken")
    public String checkwxtoken(HttpServletRequest request) {
        logger.info("check wx url");
        // 微信加密签名
        String signature = request.getParameter("signature");
        // 随机字符串
        String echostr = request.getParameter("echostr");
        // 时间戳
        String timestamp = request.getParameter("timestamp");
        // 随机数
        String nonce = request.getParameter("nonce");

        String[] str = {TOKEN, timestamp, nonce};
        Arrays.sort(str); // 字典序排序
        String bigStr = str[0] + str[1] + str[2];

        // SHA1加密
        String digest = sha1Digest(bigStr);

        // 确认请求来至微信
        if (digest.equals(signature)) {
            return echostr;
        } else {
            return "error";
        }
    }

    private String sha1Digest(String content) {
        Digest bcSha1 = DigestFactory.getDigest("SHA1");
        bcSha1.update(content.getBytes(), 0, content.getBytes().length);
        byte[] byteFinal = new byte[bcSha1.getDigestSize()];
        bcSha1.doFinal(byteFinal, 0);
        return convertBy2HexStr(byteFinal);
    }

    private String convertBy2HexStr(byte[] bytes) {
        String result = "";
        for (byte b : bytes) {
            int temp = b & 0xff;
            String tempHex = Integer.toHexString(temp);
            if (tempHex.length() < 2) {
                result += "0" + tempHex;
            } else {
                result += tempHex;
            }
        }
        return result;
    }
}
